package com.cheeven.cwliu.citation.steps;

import java.util.HashMap;
import java.util.HashSet;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Step2_1 extends StepBase {

	public static HashSet<String> getDocumentTypes(HashMap<String, String> control) {
		logInfo("2.1. Get Document Types");

		HashSet<String> documentTypes = new HashSet<String>();

		String sid = control.get("sid");
		String qid = control.get("qid");

		/* 
		 * Expand the "Document Types" section in the navigation
		 */
		String urlString = "https://apps.webofknowledge.com/RAOnSummary.do?product=UA&search_mode=GeneralSearch"
				+ "&qid=" + qid
				+ "&SID=" + sid
				+ "&colName=&ra_name=DocumentType&action=expand";

		String searchPage = httpGet(urlString);
		Document domdoc = toDOM(searchPage);

		/* 
		 * From the "Document Types" section in the navigation
		 * Click the "more options / values..." link to open the 
		 * Refine the "Document Types" page
		 */
		String raMorePageUrl = "https://apps.webofknowledge.com/" + xpath("//a[@id='DocumentType']/@href", domdoc);
		String raMorePage = httpGet(raMorePageUrl);
		domdoc = toDOM(raMorePage);

		/* 
		 * Collect all possible document types for this search result
		 */
		Element raMoreTR = (Element) xpath("//tr[@id='DocumentType_raMore_tr']", domdoc, XPathConstants.NODE);
		NodeList options = (NodeList) xpath(".//input[@name='refineSelection']/@value", raMoreTR, XPathConstants.NODESET);
		for (int i = 0; i < options.getLength(); i++) {
			Node option = options.item(i);
			documentTypes.add(option.getNodeValue());
		}

		logInfo(1, "documentTypes={0}", documentTypes);

		/* 
		 * Click "Cancel" button to return to the summary page
		 */
		String cancelUrl = xpath("//img[@title='Cancel']/../../a/@href", domdoc);
		String cancelPage = httpGet(cancelUrl);
		domdoc = toDOM(cancelPage);
		control.put("sid", xpath("//input[@name='SID']/@value", domdoc));
		control.put("qid", xpath("//input[@name='qid']/@value", domdoc));
		
		raMorePageUrl = xpath("//a[@id='DocumentType']/@href", domdoc);
		if(raMorePageUrl==null || raMorePageUrl.isEmpty()) {
			searchPage = httpGet(urlString);
			domdoc = toDOM(searchPage);
			raMorePageUrl = xpath("//a[@id='DocumentType']/@href", domdoc);
		}
		raMorePageUrl = "https://apps.webofknowledge.com/" + raMorePageUrl;
		
		control.put("raMorePageUrl", raMorePageUrl);

		return documentTypes;

	}
}
